package com.gzc.just.play.last.war.centralserver.handler;

import com.google.protobuf.ByteString;
import com.gzc.just.play.last.war.centralserver.service.UserStatusService;
import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.protobuf.gc.gctocs.GCToCS;
import com.gzc.just.play.last.war.protobuf.gs.gstocs.GSToCS;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@MessageHandler(name = "ReportGCMsgHandler", serverTypes = MessageHandler.ServerType.CENTRAL_SERVER)
public class ReportGCMsgHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(ReportGCMsgHandler.class);

    @Autowired
    private UserStatusService userStatusService;

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        GSToCS.ReportGCMsg reportMsg = null;
        if (message instanceof byte[]) {
            reportMsg = GSToCS.ReportGCMsg.parseFrom((byte[]) message);
        } else if (message instanceof GSToCS.ReportGCMsg) {
            reportMsg = (GSToCS.ReportGCMsg) message;
        }

        if (reportMsg == null) {
            logger.error("Failed to parse ReportGCMsg");
            return;
        }

        int nsid = reportMsg.getNsid();
        int otherMsgId = reportMsg.getOthermsgid();
        ByteString otherMsg = reportMsg.getOthermsg();

        // Check if it is AskLogin (8193)
        if (otherMsgId == 8193) { 
             try {
                 GCToCS.Login login = GCToCS.Login.parseFrom(otherMsg);
                 userStatusService.handleUserLogin(nsid, login, ctx);
             } catch (Exception e) {
                 logger.error("Failed to parse inner Login message", e);
             }
        } else {
             logger.debug("Received forwarded message {} from Gate for user {}", otherMsgId, nsid);
             // TODO: Dispatch to other handlers based on otherMsgId
        }
    }

    @Override
    public int getMessageId() {
        return 8195; // eMsgToCSFromGS_ReportGCMsg
    }

    @Override
    public String getName() {
        return "ReportGCMsgHandler";
    }

    @Override
    public Logger getLogger() {
        return logger;
    }
}
